import _ from "lodash";
import Util from "./util.js";
import Formatter from "./formatter.js";
import Config from "../config.js";

var upload = _.extend({}, _, {
    /**
     * 上传前压缩
     * @param {Object} srcPath 原文件路径
     * @param {Object} compressParentPath 压缩后的文件存放目录
     * @param {Object} filename 文件名
     * @param {Object} successCallback 压缩成功的回调
     */
    compress(srcPath, compressParentPath, filename, successCallback) {
        // 压缩后的文件全路径
        let compressFullPath =
            compressParentPath +
            Util.random() +
            filename.substring(filename.lastIndexOf("."), filename.length);
        if (window.plus.isWindows) {
            compressFullPath = srcPath;
        }
        // 压缩
        window.plus.zip.compressImage(
            {
                src: srcPath,
                dst: compressFullPath,
                overwrite: true,
                quality: 20
            },
            function() {
                console.log("压缩成功，开始上传：");

                if (successCallback) {
                    successCallback(compressFullPath);
                }
            },
            function() {
                console.log("压缩失败!");
            }
        );
    },

    /**
     * 删除上传时产生的临时文件
     * @param {Object} filePath 文件完整路径
     */
    deleteTmpFile(filePath) {
        window.plus.io.resolveLocalFileSystemURL(
            filePath,
            function(entry) {
                // 可通过entry对象操作文件
                entry.remove(
                    function(e) {
                        console.log("删除文件成功");
                    },
                    function(e) {
                        console.log(e.message);
                    }
                );
            },
            function(e) {
                console.log("Resolve file URL failed: " + e.message);
            }
        );
    },

    /**
     * 文件上传
     * @param {Object} filePath 文件全路径
     * @param {Object} dataKey 业务主键，如用户ID等
     * @param {Object} type 附件类型，字符串，参考AttachementType枚举
     * @param {Object} successCallback 上传成功的回调，可带一个参数接收服务器返回的数据
     */
    upload(filePath, dataKey, type = "mobile", successCallback) {
        let self = this;
        // 文件名
        let lastIndex = filePath.lastIndexOf("/");
        if (lastIndex == -1) {
            lastIndex = filePath.lastIndexOf("\\");
        }
        let name = filePath.substr(lastIndex + 1);

        console.log("filePath:" + filePath + ", name:" + name);

        let savePath = "_doc/compress/";
        if (window.plus.isWindows) {
            savePath = '';
        }

        this.compress(filePath, savePath, name, function(
            compressFullPath
        ) {
            let wt = window.plus.nativeUI.showWaiting();
            // 上传必须是全路径
            let server = Config.api.upload;
            let task = window.plus.uploader.createUpload(
                server,
                { method: "POST" },
                function(t, status) {
                    wt.close();
                    //上传完成
                    if (status == 200) {
                        if (t.responseText == '') {
                            return;
                        }
                        // TODO 可能有问题
                        let filesJSON = JSON.parse(t.responseText);
                        console.log("上传成功：" + t.responseText);

                        // 删除临时文件
                        self.deleteTmpFile(compressFullPath);

                        if (successCallback) {
                            successCallback(filesJSON);
                        }
                    } else {
                        console.error("上传失败：" + status);
                        // 删除临时文件
                        upload.deleteTmpFile(compressFullPath);
                    }
                }
            );

            task.addData("type", type);
            // 文件名，解决后台接收到的中文文件名乱码
            task.addData("filename", name);
            task.addData("dataKey", dataKey);

            // 临时解决cookie失效问题
            task.addData("uploaderId", vue.$f7.data.currentUser.userId);
            task.addData("uploaderName", vue.$f7.data.currentUser.userName);

            task.addFile(compressFullPath, {key: "file"});
            task.start();
        });
    },

    /**
     * 根据附件ID下载文件
     * @param {Object} savePath 下载后保存的路径，目录
     * @param {Object} id 附件ID
     * @param {Object} isShowLoader 是否显示加载中的图标
     * @param {Object} successCallback 下载成功后的回调，可带一个参数表示下载任务对象
     */
    idDownload(savePath = Config.api.fileSavePath, id, isShowLoader = true, successCallback) {
        var url = Config.api.download + "?attachmentId=" + id;
        upload.download(url, savePath, isShowLoader, successCallback);
    },

    /**
     * 根据dataKey和type下载文件
     * @param {Object} savePath 下载后保存的路径，目录
     * @param {Object} dataKey 业务主键，如用户ID
     * @param {Object} type 附件类型，字符串，参考AttachementType枚举
     * @param {Object} isShowLoader 是否显示加载中的图标
     * @param {Object} successCallback 下载成功后的回调，可带一个参数表示下载任务对象
     */
    typeDownload(savePath, dataKey, type, isShowLoader, successCallback) {
        var url =
            Config.api.typeDownload + "?dataKey=" + dataKey + "&type=" + type;
        upload.download(url, savePath, isShowLoader, successCallback);
    },

    /**
     * 文件下载
     * @param {Object} url 文件下载路径，根据dataKey和type下载文件
     * @param {Object} savePath 下载后保存的路径，目录或文件名
     * @param {Object} dataKey 业务主键，如用户ID
     * @param {Object} type 附件类型，字符串，参考AttachementType枚举
     * @param {Object} isShowLoader 是否显示加载中的图标
     * @param {Object} successCallback 下载成功后的回调，可带一个参数表示下载任务对象
     */
    download(url, savePath, isShowLoader, successCallback) {
        var options = {
            method: "GET",
            filename: savePath,
            retry: 2,
            timeout: 90,
            retryInterval: 20
        };
        if (isShowLoader === true) {
            var wt = window.plus.nativeUI.showWaiting();
        }
        var dtask = window.plus.downloader.createDownload(url, options);
        dtask.addEventListener("statechanged", function(task, status) {
            if (!dtask) {
                return;
            }
            switch (task.state) {
                case 1: // 开始
                    console.log("准备下载");
                    break;
                case 2: // 已连接到服务器
                    console.log("已连接到服务器");
                    break;
                case 3: // 已接收到数据
                    console.log("已接收到数据");
                    break;
                case 4: // 下载完成
                    console.log(task.filename + " , " + task.totalSize);
                    console.log("下载完成！");

                    let index = _.findLastIndex(vue.$f7.data.downloaders, downloader => {
                        return downloader.url == url;
                    });

                    if (task.totalSize > 0) {

                        vue.$f7.data.downloaders[index].name = task.filename.substr(task.filename.lastIndexOf("/") + 1);
                        vue.$f7.data.downloaders[index].state = task.state;

                        // vue.$f7.toast.create({
                        //     text: '下载完成',
                        //     closeButton: true,
                        //     closeTimeout: 5000,
                        //     closeButtonText: '点此查看',
                        //     closeButtonColor: 'white',
                        //     on: {
                        //         closeButtonClick: function () {
                        //             let sheet = vue.$f7.sheet.get();
                        //             if (sheet) {
                        //                 sheet.close();
                        //             }
                        //             vue.$f7.views.current.router.navigate("/setting/settingDown/");
                        //         },
                        //     }
                        // }).open();

                        vue.$f7.notification.create({
                            title: Config.info.name,
                            titleRightText: Formatter.formatDate(new Date(), "hh:mm"),
                            subtitle: vue.$f7.data.downloaders[index].name,
                            text: '下载完成，点此查看',
                            closeButton: true,
                            closeOnClick: true,
                            closeTimeout: 5000,
                            on: {
                              click: function () {
                                vue.$f7.views.current.router.navigate("/setting/settingDown/");
                              },
                            },
                          }).open();

                    } else {
                        vue.$f7.dialog.toast("无法连接到资源，请检查下载链接");
                        dtask.abort();
                        // 删除
                        vue.$f7.data.downloaders.splice(index, 1);
                    }

                    if (isShowLoader === true) {
                        wt.close();
                    }
                    if (successCallback) {
                        vue.$f7.dialog.close();
                        successCallback(task);
                    }
                    break;
            }
        });

        vue.$f7.data.downloaders.push({url: url, name: savePath.substr(savePath.lastIndexOf("/") + 1), state: -1, task: dtask});
        vue.$f7.toast.create({
            text: '已经添加下载任务',
            closeButton: true,
            closeTimeout: 5000,
            closeButtonText: '点此查看',
            closeButtonColor: 'white',
            on: {
                closeButtonClick: function () {
                    vue.$f7.views.current.router.navigate("/setting/settingDown/?tabActive=1");
                },
            }
        }).open();

        dtask.start();
    }
});

export default upload;
